<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

App::import('Model', 'User');
App::import('Model', 'Account');
App::import('Model', 'tattlrAccount');

class AccountsController extends AppController {

    public $helpers = array('Html', 'Form');
    public $helpers1 = array('Js' => array('DragDropHelpers'));
    public $helpers2 = array('Js' => array('EventHelpers'));
    public $helpers3 = array('Js' => array('permissionForm'));
    public $helpers4 = array('css' => array('permission'));

    public function index() {

        $this->set('accounts', $this->Account->find('all'));
    }

    /**
     * 
	 * Description of "assign_pos"
	 *
     * This function passes the arrays(unassignedUsers,moderators,editors,jEditors) from the controller 
     * to the view and then passes the new arrays from the view to the controller when the admin is done...
	 *
	 * @author karim kamel
     */
    public function assign_pos() {
        $user = new User();
		$account = new Account();
        $accID = $this->Auth->user('accID');
		if($accID == null) {
            $this->Session->setFlash('Please select an account');
        }else {
        $admin = $user->isAdmin($this->Auth->user('userID'));
        if ($admin == 1) {

            $this->set('admin', $admin);

			$namearray = $account->getAccountNameByAccID($accID);
            $name = $namearray[0]['Account']['name'];
            $this->set('name', $name);
			
            $arrayusers = $user->getUnassignedUsers($accID);
            $this->set('arrayusers', $arrayusers);
            $length = count($arrayusers);
            $this->set('length', $length);
            /** print_r($arrayusers); */
            $mod = $user->getModeratorsByName($accID);
            $this->set('mod', $mod);
            $modlen = count($mod);
            $this->set('modlen', $modlen);

            $edi = $user->getEditorsByName($accID);
            $this->set('edi', $edi);
            $edilen = count($edi);
            $this->set('edilen', $edilen);

            $jEdi = $user->getJEditorsByName($accID);
            $this->set('jEdi', $jEdi);
            $jEdilen = count($jEdi);
            $this->set('jEdilen', $jEdilen);

            if (!empty($this->request->data)) {
                $mod = $this->request->data['moderators1'];
                $ed = $this->request->data['editors1'];
                $jed = $this->request->data['jEditors1'];
                ClassRegistry::init('Account')->assignPos($mod, $ed, $jed, $accID);
            }
        } else {
            $this->Session->setFlash('you are not authorized to view this page');
        }
		}
    }

    function accountIsAuthorized($accountID) {
        if (!($this->Account->isUnique('accID', $accountID))) {
            return True;
        } else {
            return False;
        }
        //$account = $this->Account->query("select oauthToken, oauth_token_secret from accounts Account where Account.accID='" . $accountID . "'");
    }

    function connectionRequest($accountID) {
        if ($this->accountIsAuthorized($accountID)) {
            $account = $this->Account->query("select oauthToken, oauth_token_secret from accounts Account where Account.accID='" . $accountID . "'");
            $connection = new TwitterOAuth('S9Ww3avoaAONgzqU27DKMQ', 'gPcguIyyKbZlCrlBsKDIKqNCDqu558tfkRdsipoGw', $account['0']['Account']['oauthToken'], $account['0']['Account']['oauth_token_secret']);
            $content = $connection->get('account/verify_credentials');
            return $connection;
        }
        else
            return FALSE;
    }

    /**
     * A function returns a list of existing clients 
     * @param void
     * @return void
     * @author OmarElshal,
     */
    function viewClients() {
  
            $clients ['joins'] = array(
            array('table' => 'tattlr_accounts',
                'alias' => 'tattlrAccount',
                'type' => 'INNER',
                'conditions' => array(
                    'tattlrAccount.accID=Account.accID'
                )
            )
        );

        $result = $this->Account->find('all', $clients);      
        $this->set('result', $result);
    }

    /*
     * Description of "filteraccount"
     * @param  
     *
     * The function check if the user is an admin if yes it return all the accounts else it display the meesage you sre not authorized to filter by account.
     *
     * @author "Noha Diaa"
     */

    public function filteraccount() {

        //$this->set('result', null);

        $options ['joins'] = array(
            array('table' => 'tattlr_accounts',
                'alias' => 'tattlrAccount',
                'type' => 'INNER',
                'order' => array('Account.accID' => 'desc'),
                'conditions' => array(
                    'tattlrAccount.accID=Account.accID'
                )
            )
        );
        $account = new Account();
        $tweets = $account->find('all', $options);

        $this->set('result', $tweets);
    }

    public function filteraccountt($accID) {
        $acc = new tattlrAccount();
        $account = $acc->find('all', array('conditions' => array('accID' => $accID)));
        $this->set('finaltweets', null);
        if (!empty($account)) {
            $au = ClassRegistry::init('User')->getPermissionLevel('1', $accID);
            if (($this->Auth->user('admin')) == 1) {
                $account = new Account();
                $tweets = $account->query("select * from posts Post join tweets Tweet ON Post.postID=Tweet.postID where Post.accID='" . $accID . "'");
                $this->set('finaltweets', $tweets);
            } else {
                $this->Session->setFlash('you are not authorized to filter by account');
            }
        } else {
            $this->Session->setFlash('selected account doesnot exist');
        }
    }

    /**
     * Gets the followers of the authorized account
     *
     * @access: public
     *
     * @author "Hussein Abo El Seoud"
     */
    public function getFollowers() {
        $accID = $this->Auth->User('accID');
        if ($accID == null) {
            $this->redirect('/posts/fetchHome');
            return 'failed';
        }
        $this->set('ids', $this->Account->getFollowers($accID));
        $this->set('accountID', $accID);
    }

    /*
     * description of this function is in appcontroller
     * @author "Mohamed Elhawary"
     */

    public function isAuthorized($user) {
        parent::isAuthorized($user);
        if ($this->action == 'edit') {
            if ($user['admin']) {
                return true;
            } else {
                return false;
            }
        } else {
            return true;
        }
    }

    /*
     * description of edit
     * @param int $id
     * 
     * this function takes an id of account then opens a form for it to edit it and in the form 
     * changes can be saved
     * 
     * @author "Mohamed Elhawary"
     */

    public function edit($id = null) {
        if ($id == null) {
            $this->Session->setFlash('please choose an Account to edit');
            $this->set('src', 'eggs.png');
            $this->set('name', 'No account');
            $this->set('min', 'No account');
            return;
        }
        $this->Account->id = $id;
        $name = $this->Account->find('all', array('conditions' => array('Account.accID' => $id), 'fields' => 'Account.name'));
        if ($name == null) {
            $this->Session->setFlash('Could not Find Account ');
            $this->set('src', 'eggs.png');
            $this->set('name', 'No account');
            $this->set('min', 'No account');
            return;
        }
        $img = $this->Account->find('all', array('conditions' => array('Account.accID' => $id), 'fields' => 'Account.image'));
        $img = $img['0']['Account']['image'];
        if ($img == null) {
            $this->set('src', 'eggs.png');
        } else {
            $this->set('src', $img);
        }
        $name = $name['0']['Account']['name'];
        $this->set('name', $name);
        $this->loadModel('tattlrAccount');
        $this->set('min', $this->tattlrAccount->getMin($id));
        if ($this->request->is('post')) {
            $this->Account->data = $this->request->data;
            if (!($this->Account->validates())) {
                return;
            }
            if ($this->Account->saveField('name', $this->request->data['Account']['name']) && $this->tattlrAccount->updateMin($this->request->data['Account']['Minimum Duration'], $id)) {
                $this->Session->setFlash('changes saved sucessfully');
                $this->redirect(array('controller' => 'users', 'action' => 'index'));
            } else {
                $this->Session->setFlash('data could not be saved , please try again');
            }
        }
    }

    /*
     * @access: public
     * @param: $screenName
     * Description: This function connects with twitter and follows a certain account.
     * @author Ahmed El-Fouly
     */

    public function follow($screenName, $followersPage) {
        $userID = $this->Auth->User('userID');
        $accID = $this->Auth->User('accID');
        $this->loadModel('User');
        $permission = $this->User->getPermissionLevel($accID, $userID);
        if ($permission == 1) {
            $this->Session->setFlash("You're not authorized to follow/unfollow other twitter accounts from this account.");
        } else {
            $connection = $this->Account->connectionRequest($accID);
            if($connection == false) {
                $this->Session->setFlash("Something went wrong while connecting to twitter.");
                return;
            }
            $status1 = (array) $connection->post('friendships/create/' . $screenName);
            $this->Session->setFlash("This account is now following " . $screenName);
        }
        if($followersPage) {
            $this->redirect(array('controller' => 'accounts', 'action' => 'getFollowers'));
        } else {
            $this->redirect(array('controller' => 'tweets', 'action' => 'index'));
        }
        $status = (array) $this->Account->connectionRequest($accID)->get('users/show/' . ($status1['id']));
        return $status['following'];
    }

    /*
     * @access: public
     * @param: $screenName
     * Description: This function connects with twitter and unfollows a certain account.
     * @author Ahmed El-Fouly
     */

    public function unfollow($screenName, $followersPage) {
        $userID = $this->Auth->User('userID');
        $accID = $this->Auth->User('accID');
        $this->loadModel('User');
        $permission = $this->User->getPermissionLevel($accID, $userID);
        if ($permission == 1) {
            $this->Session->setFlash("You're not authorized to follow/unfollow other twitter accounts from this account.");
        } else {
            $connection = $this->Account->connectionRequest($accID);
            if($connection == false) {
                $this->Session->setFlash("Something went wrong while connecting to twitter.");
                return;
            }
            $status1 = (array) $connection->post('friendships/destroy/' . $screenName);
            $this->Session->setFlash("This account has unfollowed " . $screenName);
        }
        if($followersPage) {
            $this->redirect(array('controller' => 'accounts', 'action' => 'getFollowers'));
        } else {
            $this->redirect(array('controller' => 'tweets', 'action' => 'index'));
        }
        $status = (array) $this->Account->connectionRequest($accID)->get('users/show/' . ($status1['id']));
        return !($status['following']);
    }
    /**
     *@author Moataz Ezzo
     *This function gets list of users from model 
     */
    function viewUsers() {
        $this->_checkPermission();
        $userID = $this->Auth->User('userID');
        $accID = $this->Auth->User('accID');
        $y;
        $i = 0;
        $users = $this->Account->getUsers($accID, $userID);
        if ($users == null) {
            $this->Session->setFlash('There are no other users in this company, you are in your own!');
            return $this->redirect('/users/index/');
        }
        foreach ($users as $user) {
            $y[$i]['username'] = $user['users']['username'];
        }
        $this->set('user', $y);
    }


}
?>

